﻿using DotNetty.Transport.Channels;
using System.Threading.Tasks;
namespace Athena.Transport.DotNetty
{
    using Codec;
    using Message;
    public class DotNettyTransportMessageClientSender : DotNettyTransportMessageSender, ITransportMessageSender
    {
        private readonly IChannel _channel;

        public DotNettyTransportMessageClientSender(IRpcMessageEncoder rpcMessageEncoder, IChannel channel) : base(rpcMessageEncoder)
        {
            _channel = channel;
        }

        public void Dispose()
        {
            Task.Run(async () =>
            {
                await _channel.DisconnectAsync();
            }).Wait();
        }

        public async Task SendAsync(RpcTransportMessage rpcTransportMessage)
        {
            var buffer = GetByteBuffer(rpcTransportMessage);
            await _channel.WriteAsync(buffer);
        }

        public async Task SendAndFlushAsync(RpcTransportMessage rpcTransportMessage)
        {
            var buffer = GetByteBuffer(rpcTransportMessage);
            await _channel.WriteAndFlushAsync(buffer);
        }
    }
}
